package cn.org.donald.framework.config;

import cn.org.donald.framework.annotation.ListSize;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.List;

/**
 * Return false if list'size smaller than min or bigger than max also null
 * @author : Donald
 * @since : 2020/12/17 14:45
 */
public class ListSizeValidate implements ConstraintValidator<ListSize, List<?>> {

    private int min;

    private int max;


    // 初始化
    @Override
    public void initialize(ListSize constraintAnnotation) {
        this.min = constraintAnnotation.min();
        this.max = constraintAnnotation.max();

    }

    @Override
    public boolean isValid(List<?> list, ConstraintValidatorContext constraintValidatorContext) {
        if (list == null){
            return false;
        }
        if (this.max != -1 && this.max > this.min && list.size() > this.max) {
            return false;
        } else {
            return list.size() >= this.min;
        }
    }

}
